package com.thunder.reader.transaction;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import com.thunder.reader.FeedSettings;
import com.thunder.reader.provider.Feed;

import android.content.ContentResolver;
import android.database.Cursor;
import android.text.TextUtils;

public class BackupAgent {
    private OutputStream mOutputStream;
    private ContentResolver mContentResolver;
    
    public BackupAgent(ContentResolver cr, OutputStream os) {
        mOutputStream = os;
        mContentResolver = cr;
    }
    
    public void backup() throws IOException {
        if (mOutputStream == null) {
            throw new IOException("output stream is null, did you initialize this class correctly");
        }
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(mOutputStream);
            writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            writer.println("<foxreader version=\"1.0\">");
            addGroups(writer);
            writer.println("</foxreader>");
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
    
    private void addGroups(PrintWriter writer) throws IOException {
        Cursor cursor = null;
        try {
            cursor = mContentResolver.query(Feed.Group.CONTENT_URI, Feed.Group.PROJECTION, null, null, null);
            if (cursor == null || !cursor.moveToFirst()) {
                return; // fall through to finally clause
            }
            do {
                String title = cursor.getString(Feed.Group.TITLE_INDEX);
                String description = cursor.getString(Feed.Group.DESCRIPTION_INDEX);
                if (TextUtils.isEmpty(title)) {
                    title = Feed.Group.GROUP_DEFAULT;
                }
                if (TextUtils.isEmpty(description)) {
                    description = title;
                }
                writer.print("<group title=\"");
                title = URLEncoder.encode(title, FeedSettings.getDefaultEncoding());
                writer.print(title);
                writer.print("\" description=\"");
                description = URLEncoder.encode(description, FeedSettings.getDefaultEncoding());
                writer.print(description);
                writer.println("\">");
                // add feeds belonging to this group
                addFeeds(cursor.getString(Feed.Group.ID_INDEX), writer);
                writer.println("</group>");
            } while (cursor.moveToNext());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    
    private void addFeeds(String id, PrintWriter writer) throws IOException {
        Cursor cursor = null;
        try {
            cursor = mContentResolver.query(Feed.Source.CONTENT_URI, Feed.Source.PROJECTION, Feed.Source.GROUP_ID +"=?", 
                    new String[]{id}, null);
            if (cursor == null || !cursor.moveToFirst()) {
                return;
            }
            do {
                final String xmlUrl = cursor.getString(Feed.Source.FEED_URL_INDEX);
                if (TextUtils.isEmpty(xmlUrl)) {
                    continue;
                }
                writer.print("<source xmlUrl=\"");
                writer.print(xmlUrl);
                String title = cursor.getString(Feed.Source.TITLE_INDEX);
                if (!TextUtils.isEmpty(title)) {
                    writer.print("\" title=\"");
                    title = URLEncoder.encode(title, FeedSettings.getDefaultEncoding());
                    writer.print(title);
                }
                String description = cursor.getString(Feed.Source.DESCRIPTION_INDEX);
                if (!TextUtils.isEmpty(description)) {
                    writer.print("\" description=\"");
                    description = URLEncoder.encode(description, FeedSettings.getDefaultEncoding());
                    writer.print(description);
                }
                final String htmlUrl = cursor.getString(Feed.Source.URL_INDEX);
                if (!TextUtils.isEmpty(htmlUrl)) {
                    writer.print("\" htmlUrl=\"");
                    writer.print(htmlUrl);
                }
                final String imageUrl = cursor.getString(Feed.Source.IMAGE_URL_INDEX);
                if (!TextUtils.isEmpty(imageUrl)) {
                    writer.print("\" imageUrl=\"");
                    writer.print(imageUrl);
                }
                writer.println("\">");
                // add articles belonging to this source
                addArticles(cursor.getString(Feed.Source.ID_INDEX), writer);
                writer.println("</source>");
            } while (cursor.moveToNext());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    
    private void addArticles(String id, PrintWriter writer) throws IOException {
        Cursor cursor = null;
        try {
            cursor = mContentResolver.query(Feed.Article.CONTENT_URI, Feed.Article.PROJECTION, 
                    Feed.Article.SOURCE_ID + "=?", new String[]{id}, null);
            if (cursor == null || !cursor.moveToFirst()) {
                return;
            }
            do {
                String title = cursor.getString(Feed.Article.TITLE_INDEX);
                if (TextUtils.isEmpty(title)) {
                    continue;
                }
                writer.print("<article title=\"");
                title = URLEncoder.encode(title, FeedSettings.getDefaultEncoding());
                writer.print(title);
                String description = cursor.getString(Feed.Article.DESCRIPTION_INDEX);
                if (!TextUtils.isEmpty(description)) {
                    writer.print("\" description=\"");
                    description = URLEncoder.encode(description, FeedSettings.getDefaultEncoding());
                    writer.print(description);
                }
                final String url = cursor.getString(Feed.Article.ARTICLE_URL_INDEX);
                if (!TextUtils.isEmpty(url)) {
                    writer.print("\" articleUrl=\"");
                    writer.print(url);
                }
                final String imageUrl = cursor.getString(Feed.Article.IMAGE_URL_INDEX);
                if (!TextUtils.isEmpty(imageUrl)) {
                    writer.print("\" imageUrl=\"");
                    writer.print(imageUrl);
                }
                final String pubDate = cursor.getString(Feed.Article.PUB_DATE_INDEX);
                if (TextUtils.isEmpty(pubDate)) {
                    writer.print("\" pubDate=\"");
                    writer.print(pubDate);
                }
                writer.print("\" read=\"");
                writer.print(cursor.getString(Feed.Article.READ_INDEX));
                writer.println("\"/>");
            } while (cursor.moveToNext());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}